package com.yc.cloud.config;

import com.yc.cloud.common.config.BaseRunConfig;
import com.yc.cloud.utils.MinIoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @author 杨智杰
 * @since 2021/8/26 11:08
 */
@Slf4j
@Component
@EnableScheduling
@ConditionalOnProperty(name = "minio-config.heartbeat.is-enable", havingValue = "true")
public class RunConfig extends BaseRunConfig {

    @Resource
    private MinIoUtil minIoUtil;

    @Override
    public void run(ApplicationArguments args) {
        linkMinio();
    }

    /**
     * minio地址+端口号
     */
    @Value("${minio-config.url:http://127.0.0.1:9000}")
    public String url;

    /**
     * minio用户名
     */
    @Value("${minio-config.access-key:minioadmin}")
    public String accessKey;

    /**
     * minio密码
     */
    @Value("${minio-config.secret-key:minioadmin}")
    public String secretKey;

    /**
     * 默认文件桶的名称
     */
    @Value("${minio-config.default-bucket-name:default}")
    public String defaultBucketName;

    public void minioUtilConfig() {
        MinIoUtil.url = url;
        log.info("minio服务地址:" + MinIoUtil.url);
        MinIoUtil.accessKey = accessKey;
        log.info("minio用户名:" + MinIoUtil.accessKey);
        MinIoUtil.secretKey = secretKey;
        log.info("minio密码:" + MinIoUtil.secretKey);
        MinIoUtil.defaultBucketName = defaultBucketName;
        log.info("minio默认使用文件桶:" + MinIoUtil.defaultBucketName);
    }


    /**
     * 是否需要连接minio服务器
     */
    boolean isLink = true;

    @Scheduled(cron = "${minio-config.heartbeat.interval:30 * * * * ?}")
    public void linkMinio() {
        if (isLink) {
            minioUtilConfig();
            isLink = !minIoUtil.minioConfig();
        }
        try {
            MinIoUtil.createBucket(MinIoUtil.defaultBucketName);
            log.info("minio心跳检测正常!");
        } catch (Exception e) {
            log.error("minio服务器连接丢失!", e);
            isLink = true;
        }
    }
}
